<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>

        /*
            假设现在要请求100个url的数据，但由于某些原因，我们必须将同一时刻并发请求数量控制在 10 个以内，尽可能最快的获取所有请求返回的响应数据，请你实现这样一个函数。
            请求url可以直接用fetch(url)。
            function multiRequest(urls = [], maxNum) {
            }

            https://blog.csdn.net/weixin_42655717/article/details/118862407
        */
        const urlData = [
            "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=1",
            "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=2",
            "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=3",
            "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=4",
            "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=5",
            "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=6",
            "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=7",
            "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=8",
            "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=9",
            "https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=10",
        ];
  
  function multiRequest(urls, maxNum, callbackFunc) {
    const REQUEST_MAX = maxNum;
    const TOTAL_REQUESTS_NUM = urls.length;
    const blockQueue = []; // 等待排队的那个队列
    let currentReqNumber = 0; // 现在请求的数量是
    let numberOfRequestsDone = 0; // 已经请求完毕的数量是
    const results = new Array(TOTAL_REQUESTS_NUM).fill(false); // 所有请求的返回结果，先初始化上
  
    async function init() {
      for (let i = 0; i < urls.length; i++) {
        request(i, urls[i]);
      }
    }
  
    async function request(index, reqUrl) {
      // 这个index传过来就是为了对应好哪个请求，
      // 放在对应的results数组对应位置上的，保持顺序
      if (currentReqNumber >= REQUEST_MAX) {
        await new Promise((resolve) => blockQueue.push(resolve)); // 阻塞队列增加一个 Pending 状态的 Promise，
        // 进里面排队去吧，不放你出来，不resolve你，你就别想进行下面的请求
      }
      reqHandler(index, reqUrl); // {4}
    }
  
    async function reqHandler(index, reqUrl) {
      currentReqNumber++; // {5}
      try {
        const result = await fetch(reqUrl);
        results[index] = result;
      } catch (err) {
        results[index] = err;
      } finally { 
        currentReqNumber--;
        numberOfRequestsDone++;
        if (blockQueue.length) {
          // 每完成一个就从阻塞队列里剔除一个
          blockQueue[0](); // 将最先进入阻塞队列的 Promise 从 Pending 变为 Fulfilled，
          // 也就是执行resolve函数了，后面不就能继续进行了嘛
          blockQueue.shift();
        }
        if (numberOfRequestsDone === TOTAL_REQUESTS_NUM) {
          callbackFunc(results);
        }
      }
    }
  
    init();
  }
  
   multiRequest(urlData, maxNum = 10, (result) => console.log(result));
  
  
    </script>
</body>
</html>